package com.zhangkunhao.notes.utils;

import com.baidu.aip.contentcensor.AipContentCensor;
import com.zhangkunhao.notes.entity.bo.LegalWordsDetector;
import org.json.JSONArray;
import org.json.JSONObject;


/**
 * 文本非法内容检验的工具类
 *
 * @author 20642
 */
public class IllegalWordsDetectorUtils {
    /**
     * 账户：18307687723
     * 用户名：bili-bili-zhang-kunhao
     * 密码：
     * 获取百度智能云上设置的APPID/AK/SK
     */
    private static final String APP_ID = "32997755";
    private static final String API_KEY = "sHxGd3iPz7woG9KpsGc2dhpw";
    private static final String SECRET_KEY = "S1RuhsKxawhdUKsD1ILDALamAc5mrdNp";

    /**
     * 创建AipContentCensor客户端
     */
    private static final AipContentCensor CLIENT = new AipContentCensor(APP_ID, API_KEY, SECRET_KEY);

    /**
     * 检测文本中是否包含敏感词汇
     *
     * @param content：
     * @return LegalWordsDetector
     */
    public static LegalWordsDetector isLegalWords(String content) {
        //封装返回的结果
        LegalWordsDetector checkBean = new LegalWordsDetector(true, "数据合规");

        // 调用文本审核接口
        JSONObject response = CLIENT.textCensorUserDefined(content);
        System.out.println(response);

        // 判断审核结果是否包含敏感词汇，conclusion=合规或者不合规
        if (response.has("conclusion")) {

            String conclusion = response.getString("conclusion");

            if ("不合规".equals(conclusion) && response.has("data")) {

                JSONArray dataArray = response.getJSONArray("data");

                for (Object o : dataArray) {

                    //强转拿数据
                    JSONObject data = (JSONObject) o;
                    String msg = data.getString("msg");

                    //修改封装结果
                    checkBean.setIsLegal(false);
                    checkBean.setMsg(msg);

                    //结束
                    return checkBean;

                }
            }
        }
        return checkBean;
    }

    public static void main(String[] args) {
        String content = "你好";
        LegalWordsDetector checkBean = isLegalWords(content);
        System.out.println(checkBean);
        String content1 = "找小姐";
        LegalWordsDetector checkBean1 = isLegalWords(content1);
        System.out.println(checkBean1);
    }
}